package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.entity.Address;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {



    @Override
    @Transactional    //开启事务
    public void updateuserMoneyById(long id, Integer money) {
        //1，查询用户
//        this.getById(id);
//        baseMapper.selectById(id);
        User user = getById(id);
        //2，检验用户状态
        if(user == null || user.getStatus()==UserStatus.FROZEN){
            throw new RuntimeException("用户状态异常！");
        }

        //3，校验余额是否充足
        if(user.getBalance()<money){
            throw new RuntimeException("用户余额不足！");
        }
        //4，扣减余额
//        baseMapper.deductBalance(id,money)
        int remainBalance = user.getBalance() - money; //剩余余额
        lambdaUpdate()
                .set(User::getBalance,remainBalance)
                .set(remainBalance ==0,User::getStatus,UserStatus.FROZEN)
                .eq(User::getId,user.getId())
                .eq(User::getBalance,user.getBalance())  //加上乐观锁
                .update();


    }

    /**
     * 根据复杂条件查询用户
     * @param name
     * @param status
     * @param minBalance
     * @param maxBalance
     * @return
     */

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {

//        lambdaQuery()
//                .like(name!=null,User::getUsername,name)
//                .eq(status!=null,User::getStatus,status)
//                .ge(minBalance!=null,User::getUsername,minBalance)   //大于等于
//                .le(maxBalance!=null,User::getUsername,maxBalance)   //小于等于
//                .list();

        return lambdaQuery()
                .like(name!=null,User::getUsername,name)
                .eq(status!=null,User::getStatus,status)
                .ge(minBalance!=null,User::getBalance,minBalance)   //大于等于
                .le(maxBalance!=null,User::getBalance,maxBalance)   //小于等于
                .list();
//                .one();
//                .page();
    }

    @Autowired
    private AddressServiceImpl addressService;

    @Override
    public UserVO getUserAndAddressById(Long userId) {

        //1,获取用户
        User user = getById(userId);
        if(user == null || user.getStatus() == UserStatus.FROZEN){
            throw new RuntimeException("用户为空或状态异常！");
        }
        //2，获取用户的收货地址
        List<Address> address = Db.lambdaQuery(Address.class).eq(Address::getUserId, userId).list();
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        if(CollUtil.isNotEmpty(address)){
            //将Address转换为AddressVO
            userVO.setAddresses(BeanUtil.copyToList(address, AddressVO.class));
        }
        return userVO;
    }

    //根据id批量查询用户和用户的所有收货地址接口
    @Override
    public List<UserVO> queryBatchUsersAndAdressByIds(List<Long> ids) {

        //1，获取所有用户
        List<User> users = listByIds(ids);
        if(CollUtil.isEmpty(users)){  //用户集合为空
            return Collections.emptyList();
        }
        //2，获取收货地址
        //2.1 获取用户id
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        //2.2 通过用户id获取地址
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        //2.3 根据用户id，将地址进行分组
        Map<Long, List<AddressVO>> listMap = new HashMap<>();
        if(CollUtil.isNotEmpty(addressVOS)){
            listMap = addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }


        List<UserVO> userVOS = new ArrayList<>(users.size());
        //3.转换为VO
        for (User user : users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setAddresses(listMap.get(user.getId()));
            userVOS.add(userVO);
        }
        return userVOS;
    }

    //通过用户id获取用户地址
    @Override
    public UserVO getAddressById(Long id) {

        //1,获取用户
        User user = getById(id);
        //2，进行状态验证
        if(user==null||user.getStatus()== UserStatus.FROZEN){
            throw new RuntimeException("用户状态异常，已被冻结！");
        }
        //3，获取用户收获地址
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        if(CollUtil.isEmpty(addresses)){
            throw new RuntimeException("用户未设置收货地址！");
        }
        //转化PO为VO
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        userVO.setAddresses(addressVOS);
        return userVO;
    }

    // 根据复杂条件分页查询用户接口
    @Override
    public PageDTO<UserVO> PageQuerysers(UserQuery userQuery) {

        //1.1设置分页条件
        Page<User> page = userQuery.getMpPageDefaultUpdateTime();

        //1.2设置查询条件，获取返回结果
        Page<User> p = lambdaQuery()
                .like(userQuery.getName() != null,User::getUsername, userQuery.getName())
                .eq(userQuery.getStatus() != null,User::getStatus, userQuery.getStatus())
                .page(page);

        //2,数据返回
//        return PageDTO.of(p, UserVO.class);
        return PageDTO.of(p, user -> {
            //1，基础属性拷贝
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
            //2，特殊逻辑操作处理
            vo.setUsername(vo.getUsername().substring(0,vo.getUsername().length()-2)+"**");
            return vo;
        });
    }

}
